﻿/*Author：Lary Pan(itolmqj123@gmail.com)
 *Date  ：2016/6/19
 *Tips  ：配置管理类
 * */
using UnityEngine;

using System;
using System.Collections.Generic;
using System.Reflection;

using MiniJSON;

/// <summary>
/// 实体基类(每个配置类必须有唯一id)
/// </summary>
public class EntityBase { public int id; }


public class ConfigManager : ISingleton<ConfigManager>, IManager
{
	private const string Conifg_Root_Path = "Config";

	private Dictionary<Type, List<EntityBase>> allConfigDict;

	public void Init()
	{
        allConfigDict = new Dictionary<Type, List<EntityBase>>();
	}

	public void DoDestroy()
	{
        allConfigDict.Clear();
        allConfigDict = null;
	}

	//获取T的配置
    public List<T> GetConfigs<T>() where T : EntityBase
	{
		Type t = typeof(T);
        if (!allConfigDict.ContainsKey(t))
            _DoParse(t);
        List<T> list = new List<T>();
        foreach (EntityBase item in allConfigDict[t])
        {
            list.Add(item as T);
        }
        return list;
	}

	//通过id获取唯一T
	public T GetById<T>(int id) where T : EntityBase
	{
        List<T> list = this.GetConfigs<T>();
        T t = list.Find(item => item.id == id);
        if (t == null)
        {
            Debugger.LogError("Check Table {0}, can't have id:{1}", typeof(T), id);
        }
        return t;
	}

	/// <summary>
	/// 解析表格
	/// </summary>
	/// <param name="t"></param>
	private void _DoParse(Type t) 
	{
		string configPath = string.Format("{0}/{1}", Conifg_Root_Path, t.ToString());
        allConfigDict.Add(t, new List<EntityBase>());
		ResHelper.LoadLocalRes(configPath, (obj) => {
			TextAsset mJsonAsset = (TextAsset)obj;
            Dictionary<string, object> jsonData = Json.Deserialize(mJsonAsset.text) as Dictionary<string, object>;
            foreach (var item in jsonData)
            {
                allConfigDict[t].Add(CHelper.DecodeJson(t, (Dictionary<string, object>)item.Value));
            }
		});
	}
}
